package jbrowser.services;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import jbrowser.JBrowser;

/**
 *
 * @author suse
 */
public class DefaultConfigurationService implements ConfigurationService {

    private static final Logger logger = Logger.getLogger(DefaultConfigurationService.class.getName());
    private File etcFolder;

    public DefaultConfigurationService() {
        etcFolder = new File(JBrowser.getHome(), "etc");
        if (!etcFolder.exists()) {
            etcFolder.mkdir();
        }
    }

    @Override
    public Properties getProperties(String name) {
        return getProperties(name, null);
    }

    @Override
    public Properties getProperties(String name, Properties defaults) {
        FileInputStream fis = null;
        try {
            Properties properties = new Properties(defaults);
            File file = new File(etcFolder, name);
            fis = new FileInputStream(file);
            properties.load(fis);
            return properties;
        } catch (Exception ex) {
            logger.log(Level.SEVERE, null, ex);
            return null;
        } finally {
            try {
                fis.close();
            } catch (Exception ex) {
                logger.log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public void setProperties(String name, Properties properties) {
        FileOutputStream fos = null;
        try {
            File file = new File(etcFolder, name);
            fos = new FileOutputStream(file);
            properties.store(fos, null);
        } catch (Exception ex) {
            logger.log(Level.SEVERE, null, ex);
        } finally {
            try {
                fos.close();
            } catch (Exception ex) {
                logger.log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public void addProperties(String name, Properties properties) {
        File file = new File(etcFolder, name);
        if (file.exists()) {
            Properties oldProperties = getProperties(name);
            for (String key : properties.stringPropertyNames()) {
                oldProperties.setProperty(key, properties.getProperty(key));
            }
            setProperties(name, oldProperties);
        } else {
            setProperties(name, properties);
        }
    }

    @Override
    public String getName() {
        return "DefaultConfigurationService";
    }

    @Override
    public Set<String> getPropertyNames() {
        File[] files = etcFolder.listFiles();
        Set<String> names = new HashSet<String>(files.length);
        for (File file : files) {
            names.add(file.getName());
        }
        return names;
    }
}
